import { login, logout, getInfo, refreshToken } from '@/api/login'
import { getToken, setToken, setExpiresIn, removeToken } from '@/utils/auth'
import { isEmpty } from '@/utils/validate'
import defAva from '@/assets/images/user_icon.png'

// 定义状态类型
interface UserState {
  token: string
  id: string
  name: string
  avatar: string
  roles: string[]
  permissions: string[]
  deptId: string
  expires_in: string | number
}

const user = {
  state: {
    token: getToken(),
    id: '',
    name: '',
    avatar: '',
    roles: [],
    permissions: [],
    deptId: '',
    expires_in: '', // 添加缺失的属性
  } as UserState,

  mutations: {
    SET_TOKEN: (state: UserState, token: string) => {
      state.token = token
    },
    SET_EXPIRES_IN: (state: UserState, time: string | number) => {
      state.expires_in = time
    },
    SET_ID: (state: UserState, id: string) => {
      state.id = id
    },
    SET_NAME: (state: UserState, name: string) => {
      state.name = name
    },
    SET_AVATAR: (state: UserState, avatar: string) => {
      state.avatar = avatar
    },
    SET_ROLES: (state: UserState, roles: string[]) => {
      state.roles = roles
    },
    SET_PERMISSIONS: (state: UserState, permissions: string[]) => {
      state.permissions = permissions
    },
    SET_DEPTID: (state: UserState, deptId: string) => {
      state.deptId = deptId
    },
  },

  actions: {
    // 登录
    Login({ commit }: { commit: <T>(type: string, payload?: T) => void }, userInfo: any) {
      const username = userInfo.username.trim()
      const password = userInfo.password
      const code = userInfo.code
      const uuid = userInfo.uuid
      const mobileCode = userInfo.mobileCode
      return new Promise<void>((resolve, reject) => {
        login(username, password, code, uuid, mobileCode)
          .then((res) => {
            const data = res.data
            setToken(data.access_token)
            commit('SET_TOKEN', data.access_token)
            setExpiresIn(data.expires_in)
            commit('SET_EXPIRES_IN', data.expires_in)
            resolve()
          })
          .catch((error) => {
            reject(error)
          })
      })
    },

    // 获取用户信息
    GetInfo({ commit }: { commit: <T>(type: string, payload: T) => void; state: UserState }) {
      return new Promise<any>((resolve, reject) => {
        getInfo({
          t: Date.now(),
        })
          .then((res) => {
            const user = res.user
            const avatar = isEmpty(user.avatar) ? defAva : user.avatar
            if (res.roles && res.roles.length > 0) {
              // 验证返回的roles是否是一个非空数组
              commit('SET_ROLES', res.roles)
              commit('SET_PERMISSIONS', res.permissions)
            } else {
              commit('SET_ROLES', ['ROLE_DEFAULT'])
            }
            commit('SET_ID', user.userId)
            commit('SET_NAME', user.userName)
            commit('SET_AVATAR', avatar)
            commit('SET_DEPTID', user.deptId)
            resolve(res)
          })
          .catch((error) => {
            reject(error)
          })
      })
    },

    // 刷新token
    RefreshToken({ commit }: { commit: <T>(type: string, payload: T) => void; state: UserState }) {
      return new Promise<void>((resolve, reject) => {
        refreshToken()
          .then((res) => {
            setExpiresIn(res.data)
            commit('SET_EXPIRES_IN', res.data)
            resolve()
          })
          .catch((error) => {
            reject(error)
          })
      })
    },

    // 退出系统
    LogOut({ commit }: { commit: <T>(type: string, payload: T) => void; state: UserState }) {
      return new Promise<void>((resolve, reject) => {
        logout()
          .then(() => {
            commit('SET_TOKEN', '')
            commit('SET_ROLES', [])
            commit('SET_PERMISSIONS', [])
            removeToken()
            resolve()
          })
          .catch((error) => {
            reject(error)
          })
      })
    },

    // 前端 登出
    FedLogOut({ commit }: { commit: <T>(type: string, payload: T) => void }) {
      return new Promise<void>((resolve) => {
        commit('SET_TOKEN', '')
        removeToken()
        resolve()
      })
    },
  },
}

export default user
